#!/bin/bash

site_schedd=$1
site_cm=$2
tar_path=$3
mon_metrics=$4
datetime=`date +%s`
basejdlpath="basemon.jdl"
objjdlpath="objmon.jdl"
sed "s/objtar/$tar_path/g" $basejdlpath > $objjdlpath 

recordjobidinsqlite(){
    sqlitedb="./remotemon.db"
    datetime=$1
    site=$2
    pool=$3
    jobid=$4
    jobstat=$5
    sqlite3 $sqlitedb "insert into samjobtask values ($datetime,'$site','$pool',$jobid,$jobstat,86400,864000)"
}
# to submit pilot to site, the proper authentication method is needed
export _condor_SEC_CLIENT_AUTHENTICATION_METHODS=CLAIMTOBE
# submit pilot job to site
logger "/usr/bin/condor_submit ${objjdlpath} -remote ${site_schedd} -pool ${site_cm} |grep submitted "
submitresult=`/usr/bin/condor_submit ${objjdlpath} -remote ${site_schedd} -pool ${site_cm} |grep submitted `
if [ "$submitresult" == "" ];then
    sitemonmsg="$0 sitesched:${site_schedd} sitesched:${site_cm} jobstat:-1 tm:$datetime metrics:$mon_metrics"
else
    job_id=${submitresult##* }
    job_id=${job_id%%.*}
    logger "/usr/bin/condor_q ${job_id} -af jobstatus -name ${site_schedd} -pool ${site_cm}"
    jobstat=`/usr/bin/condor_q ${job_id} -af jobstatus -name ${site_schedd} -pool ${site_cm}`
    sitemonmsg="$0 sitesched:${site_schedd} sitecm:${site_cm} jobid:$job_id jobstat:$jobstat tm:$datetime metrics:$mon_metrics"
    recordjobidinsqlite $datetime ${site_schedd} ${site_cm} $job_id $jobstat
fi
logger $sitemonmsg

